package com.qxzn.app.personalcenter.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.ProvinceBean;
import com.qxzn.app.bean.UserInfoBean;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.page.util.GlideImageLoader;
import com.qxzn.app.page.view.CustomItemView;
import com.qxzn.app.personalcenter.R;
import com.qxzn.app.personalcenter.R2;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.Constant;
import com.qxzn.app.util.DisplayUtil;
import com.qxzn.app.util.FileUtil;
import com.qxzn.app.util.SharePreferenceUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import news.jaywei.com.compresslib.CompressTools;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 个人信息
 */
public class PersonalInfoActivity extends BaseActivity {
    @BindView(R2.id.ll_root)
    LinearLayout llRoot;
    @BindView(R2.id.civ_head)
    CustomItemView civHead;
    @BindView(R2.id.civ_nickname)
    CustomItemView civNickname;
    @BindView(R2.id.civ_id)
    CustomItemView civId;
    @BindView(R2.id.civ_sex)
    CustomItemView civSex;
    @BindView(R2.id.civ_address)
    CustomItemView civAddress;
    private String faceIdPath;
    private List<String> mSelected;
    private Call<UserInfoBean> call;
    private OptionsPickerView<String> sexOptions;
    private int sexPosition;
    private int cityPos, provincePos;
    List<String> sexList = new ArrayList<>();
    private OptionsPickerView<String> cityOptions;
    private List<String> provinceList = new ArrayList<>();
    private List<List<String>> cityList = new ArrayList<>();
    private List<List<List<String>>> areaList = new ArrayList<>();

    @Override
    protected int initLayout() {
        return R.layout.activity_personal_info;
    }

    @Override
    protected void initView() {
//        llRoot.getViewTreeObserver().addOnGlobalLayoutListener(() -> setStatusBar());
    }

    @Override
    protected void iniTitleBar() {
        tv_title.setText("个人信息");
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        civNickname.setRightEditText(SharePreferenceUtil.getNickname(this));
        civId.setRightEditText(SharePreferenceUtil.getPhone(this));
        civSex.setRightText(SharePreferenceUtil.getSex(this));
        civAddress.setRightText(SharePreferenceUtil.getAddress(this));
        Glide.with(this).load(SharePreferenceUtil.getPortrait(this)).apply(RequestOptions.bitmapTransform(new CircleCrop()).placeholder(R.mipmap.logo).error(R.mipmap.logo)).into(civHead.getIvRightIcon());
        getUserInfo();
    }

    @OnClick({R2.id.civ_head, R2.id.tv_save, R2.id.civ_sex, R2.id.civ_address})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.civ_head) {
            getPermission();
        } else if (i == R.id.tv_save) {
            if (TextUtils.isEmpty(civNickname.getRightEditText())) {
                AppUtil.showToast(this, civNickname.getRightEditHintText());
                return;
            }
            if (TextUtils.isEmpty(civId.getRightEditText())) {
                AppUtil.showToast(this, civId.getRightEditHintText());
                return;
            }
            if (TextUtils.equals("请选择性别", civSex.getRightText())) {
                AppUtil.showToast(this, "请选择性别");
                return;
            }
            if (TextUtils.equals("请选择城市", civAddress.getRightText())) {
                AppUtil.showToast(this, "请选择城市");
                return;
            }
            updateUserInfo();
        } else if (i == R.id.civ_sex) {
            showSexPicker();
        } else if (i == R.id.civ_address) {
            showCityPicker();
        }
    }

    private void getUserInfo() {
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), "{\"username\":\"" + SharePreferenceUtil.getUserName(this) + "\"}");
        call = HttpRequest.getService().getUserInfo(body);
        call.enqueue(new Callback<UserInfoBean>() {
            @Override
            public void onResponse(Call<UserInfoBean> call, Response<UserInfoBean> response) {
                UserInfoBean bean = response.body();
                if (bean != null && bean.getCode() == 200) {
                    List<UserInfoBean.DataBean> userList = bean.getData();
                    if (userList != null && userList.size() > 0) {
                        UserInfoBean.DataBean dataBean = userList.get(0);
                        if (dataBean != null) {
                            civNickname.setRightEditText(dataBean.getNiname());
                            civId.setRightEditText(dataBean.getPhone());
                            civSex.setRightText(dataBean.getGender() == 1 ? "男" : "女");
                            civAddress.setRightText(dataBean.getCity());
                            Glide.with(PersonalInfoActivity.this).load(HttpRequest.BASE_URL + dataBean.getHeadportrait()).apply(new RequestOptions().placeholder(R.mipmap.logo).error(R.mipmap.logo)).into(civHead.getIvRightIcon());
                            saveUserInfo(dataBean);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<UserInfoBean> call, Throwable t) {
                AppUtil.showToast(PersonalInfoActivity.this, "网络有点问题，请稍后再试！");
            }
        });
    }

    public void saveUserInfo(UserInfoBean.DataBean bean) {
        SharePreferenceUtil.setPortrait(this, HttpRequest.BASE_URL + bean.getHeadportrait());
        SharePreferenceUtil.setNickname(this, bean.getNiname());
        SharePreferenceUtil.setAge(this, bean.getAge());
        SharePreferenceUtil.setSex(this, bean.getGender() == 1 ? "男" : "女");
        SharePreferenceUtil.setPhone(this, bean.getPhone());
        SharePreferenceUtil.setRoles(this, bean.getRoles());
        SharePreferenceUtil.setAddress(this, bean.getCity());
    }

    private void updateUserInfo() {
        JSONObject params = new JSONObject();
        params.put("username", SharePreferenceUtil.getUserName(this));
        params.put("niname", civNickname.getRightEditText());
        params.put("phone", civId.getRightEditText());
        params.put("gender", sexPosition + 1);
        params.put("province", provinceList.get(provincePos));
        params.put("city", civAddress.getRightText());
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), JSON.toJSON(params) + "");
        Call<BaseBean> call = HttpRequest.getService().updateUserInfo(body);
        call.enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                BaseBean bean = response.body();
                if (bean != null && !TextUtils.isEmpty(bean.getMsg())) {
                    AppUtil.showToast(PersonalInfoActivity.this, bean.getMsg());
                    if (bean.getCode() == 200) {
                        setResult(RESULT_OK);
                        finish();
                    }
                    return;
                }
                AppUtil.showToast(PersonalInfoActivity.this, "用户信息修改失败");
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                AppUtil.showToast(PersonalInfoActivity.this, "网络有点问题，请稍后再试！");
            }
        });
    }

    private void updateUserPortrait(File file) {
        MultipartBody.Part fileBody = HttpRequest.getPartFileBody(file);
        RequestBody username = HttpRequest.getPartBody(SharePreferenceUtil.getUserName(this));
        Call<BaseBean> call = HttpRequest.getService().updateUserPortrait(username, fileBody);
        call.enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                BaseBean bean = response.body();
                if (bean != null && !TextUtils.isEmpty(bean.getMsg())) {
                    AppUtil.showToast(PersonalInfoActivity.this, bean.getMsg());
                    if (bean.getCode() == 200) {
                        setResult(RESULT_OK);
                    }
                    return;
                }
                AppUtil.showToast(PersonalInfoActivity.this, "头像修改失败");
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                AppUtil.showToast(PersonalInfoActivity.this, "网络有点问题，请稍后再试！");
            }
        });
    }

    private void showSexPicker() {
        if (sexOptions == null) {
            sexOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int option2, int options3, View v) {
                    sexPosition = options1;
                    civSex.setRightText(sexList.get(options1));
                }
            }).setTitleText("请选择性别").setSubmitColor(getResources().getColor(R.color.white)).setCancelColor(getResources().getColor(R.color.main_blue))
                    .setTitleBgColor(getResources().getColor(R.color.main_blue)).setTitleColor(getResources().getColor(R.color.white)).build();
            sexList.add("男");
            sexList.add("女");
            sexOptions.setPicker(sexList);
        }
        sexOptions.show();
    }

    private void showCityPicker() {
        if (cityOptions == null) {
            cityOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int option2, int options3, View v) {
                    provincePos = options1;
                    cityPos = option2;
                    civAddress.setRightText(cityList.get(options1).get(option2));
                    AppUtil.showLog(cityList.get(options1).get(option2));
                }
            }).setTitleText("请选择城市").setSubmitColor(getResources().getColor(R.color.white)).setCancelColor(getResources().getColor(R.color.main_blue))
                    .setTitleBgColor(getResources().getColor(R.color.main_blue)).setTitleColor(getResources().getColor(R.color.white)).build();
            List<ProvinceBean> provinceBeanList = JSONArray.parseArray(AppUtil.getAssetsText(this, "citys.json"), ProvinceBean.class);
            List<ProvinceBean.CityBean> city;
            for (ProvinceBean provinceBean : provinceBeanList) {//遍历省份
                List<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
//                List<List<String>> areaList = new ArrayList<>();//该省的所有地区列表（第三极）
                city = provinceBean.getCity();
                for (ProvinceBean.CityBean cityBean : city) {//遍历该省份的所有城市
                    cityList.add(cityBean.getName());//添加城市
//                    areaList.add(cityBean.getArea());//添加该所有地区数据
                }
                this.provinceList.add(provinceBean.getName());
                this.cityList.add(cityList);
//                this.areaList.add(areaList);
            }
            cityOptions.setPicker(provinceList, cityList);
        }
        cityOptions.show();
    }

    private void getPermission() {
        new RxPermissions(this).requestEachCombined(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(permission -> {
                    if (permission.granted) {
                        getPicture(1, 0);
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        showPermissionDialog("该功能需要存储权限和相机权限", (dialog, which) -> {
                            getPermission();
                        });
                    } else {
                        showPermissionDialog("该功能需要存储权限和相机权限");
                    }
                });
    }

    private void getPicture(int maxSelectable, int requestCode) {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .capture(true)
                .maxSelectable(maxSelectable)
                .captureStrategy(new CaptureStrategy(true, Constant.authority))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideImageLoader.Glide4Engine())
                .forResult(requestCode);
    }

    private void compressImg() {
        File file = new File(faceIdPath);
        AppUtil.showLog(file.exists() + "：路径：" + file);
        CompressTools tool = new CompressTools.Builder(this).setDestinationDirectoryPath(FileUtil.getBaseImagePath(this)).build();
        tool.compressToFileJni(file, new CompressTools.OnCompressListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(File file) {
                AppUtil.showLog(file.exists() + "压缩成功：" + file);
                searchFaceId(file);// TODO: 2019/8/15 人脸验证测试改回头像上传
            }
        });
    }

    private void searchFaceId(File file) {// TODO: 2019/8/15 测试人脸验证
        RequestBody device_id = HttpRequest.getPartBody(SharePreferenceUtil.getDeviceId(this));
        MultipartBody.Part fileBody = HttpRequest.getPartFileBody(file);
        Call<BaseBean> call = HttpRequest.getService().searchFaceId(device_id, fileBody);
        call.enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {

            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == RESULT_OK) {
            mSelected = Matisse.obtainPathResult(data);
            AppUtil.showLog("mSelected: " + mSelected + "\n");
            if (mSelected != null && mSelected.size() > 0) {
                faceIdPath = mSelected.get(0);
                Glide.with(this).load(faceIdPath).apply(new RequestOptions().override(DisplayUtil.dip2px(this, 80))).into(civHead.getIvRightIcon());
                compressImg();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (call != null) {
            call.cancel();
        }
    }
}
